package com.yaodian100.ec.generatepage.web;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.generate.entity.GenerateAdvertise;
import com.yaodian100.ec.generate.entity.GenerateContent;
import com.yaodian100.ec.generate.entity.GeneratePosition;
import com.yaodian100.ec.generate.service.GenerateService;

public class IdxHotSaleV5Action extends ActionSupport implements Preparable {
	
	private static final long serialVersionUID = -6447091779333475768L;
	
	private final Logger logger = LoggerFactory.getLogger(IdxHotSaleV5Action.class);
	
	private GenerateService generateService;
	
	private GenerateAdvertise advertise;
	
	private GeneratePosition position;
	
	private GenerateContent content;
	
	private StringBuilder contents;
	
	/**
	 * 广告ID
	 */
	private String advId;
	
	/**
	 * 广告状态
	 * 
	 * 00: 草稿, 10: 发送, 20: 放送中, 80: 过期, 90: 占停
	 */
	private String advStatus;
	
	/**
	 * OPTION CODE
	 */
	private String advType = "IDX_HOTSALE_V5";
	
	/**
	 * 广告名称
	 */
	private String advName;
	
	/**
	 * 广告起始日
	 */
	private String startDate;
	
	/**
	 * 广告结束日
	 */
	private String endDate;

	/**
	 * 广告起始时间
	 */
	private String startTime;

	/**
	 * 广告结束时间
	 */
	private String endTime;
	
	/**
	 * 商品编号
	 */
	private String[] prodId;
	
	/**
	 * 商品小标
	 */
	private String[] brief;
	
	/**
	 * 商品名称
	 */
	private String[] prodName;
	
	/**
	 * 广告代码(非必填)
	 */
	private String[] adWord;
	
	private String createUser;
	private Date createDate;
	private String modifyUser;
	private Date modifyDate;
	private String from;
	
	/**
	 * 日期格式化
	 */
	protected final DateFormat PATTERN_DATE_FORMAT = new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
	
	private final int AD_SIZE = 4;
	
	/**
	 * 新增首页热销商品广告
	 * 
	 * @return
	 */
	public String addIdxHotSale() {
		advId = "";
		
		if( StringUtils.equalsIgnoreCase(from, "PCL") ) {
			advType = "PCL_HOTSALE_V5";
		} else {
			advType = "IDX_HOTSALE_V5";
		}
		
		initVariables();
		return "editIdxHotSale";
	}
	
	/**
	 * 儲存首页热销商品广告
	 * 
	 * @return
	 * @throws ParseException, Exception 
	 */
	public String saveIdxHotSale() throws ParseException, Exception {
		boolean boo = false;
		
		if(idxHotSaleValidate()) {
			contents = new StringBuilder("");
			// 组properties content
			for(int i = 0; i < AD_SIZE; i++) { 
				int x = i + 1;
				contents.append("prodId"+x+"=").append(prodId[i]).append("\n")
					.append("brief"+x+"=").append(brief[i]).append("\n")
					.append("prodName"+x+"=").append(prodName[i]).append("\n");
				
				if(StringUtils.isNotBlank(adWord[i]))
					contents.append("adWord"+x+"=").append(adWord[i]).append("\n");
			}
			
			if(StringUtils.isBlank(advId)) {
				advertise = new GenerateAdvertise();
				position = new GeneratePosition();
				content = new GenerateContent();
			} else {
				advertise = generateService.get(Long.parseLong(advId));
				position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
				content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			}
			// set advertise
			advertise.setAdvType(advType);
			advertise.setAdvName(advName.trim());
			advertise.setStartDate(PATTERN_DATE_FORMAT.parse(startDate + " " + startTime + ":00"));
			advertise.setEndDate(PATTERN_DATE_FORMAT.parse(endDate + " " + endTime + ":59"));
			advertise.setAdvStatus(advStatus);
			content.setContents(contents.toString());

			if (StringUtils.countMatches(content.getContents(), "prodId") == AD_SIZE) {
				if (StringUtils.isBlank(advId)) { // advId空值走insert
					boo = generateService.saveGenerateCombine(advertise, position, content);
				} else { // advId有值走update
					boo = generateService.updateGenerateCombine(advertise, position, content);
				}
			} else {
				boo = false;
			}
			contents.setLength(0);
			
			// 存檔後執行产档逻辑
			if( StringUtils.equalsIgnoreCase(from, "PCL") ) {
				generateService.generaterPclHotSaleV5();
			} else {
				generateService.generaterIdxHotSaleV5();
			}
			
			if (!boo) {
				return "editIdxHotSale";
			} else {
				advId = advertise.getId().toString();
				addActionMessage("储存成功");
				return editIdxHotSale();
			}
		}
		return "editIdxHotSale";
	}
	
	/**
	 * 编辑首页热销商品广告
	 * 
	 * @return
	 * @throws IOException 
	 */
	public String editIdxHotSale() throws IOException {
		initVariables();
		
		if(!StringUtils.isBlank(advId)) {
			advertise = generateService.get(Long.parseLong(advId));
			position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
			content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			
			advStatus = advertise.getAdvStatus();
			advType = advertise.getAdvType();
			advName = advertise.getAdvName();
			
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getStartDate());
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getEndDate());
			startTime = FastDateFormat.getInstance("HH:mm").format(advertise.getStartDate());
			endTime = FastDateFormat.getInstance("HH:mm").format(advertise.getEndDate());
			
			createUser = advertise.getCreateUser();
			createDate = advertise.getCreateDate();
			modifyUser = advertise.getModifyUser();
			modifyDate = advertise.getModifyDate();
			
			readPropertise(content);
		}
		
		return "editIdxHotSale";
	}
	
	public String cloneIdxHotSale() throws IOException {
		initVariables();
		
		if(!StringUtils.isBlank(advId)) {
			advertise = generateService.get(Long.parseLong(advId));
			position = generateService.getGeneratePositionByAdvId(Long.parseLong(advId)).get(0);
			content = generateService.getGenerateContentByAdvId(Long.parseLong(advId)).get(0);
			
			GenerateAdvertise tmp_advertise = new GenerateAdvertise();
			BeanUtils.copyProperties(advertise, tmp_advertise, new String[] {"id", "createDate", "createUser", "modifyUser", "modifyDate"});
			advertise = tmp_advertise;
			
			GeneratePosition tmp_position = new GeneratePosition();
			BeanUtils.copyProperties(position, tmp_position, new String[] {"id", "advId", "createDate", "createUser", "modifyUser", "modifyDate"});
			position = tmp_position;
			
			GenerateContent tmp_content = new GenerateContent();
			BeanUtils.copyProperties(content, tmp_content, new String[] {"id", "advId", "createDate", "createUser", "modifyUser", "modifyDate"});
			content = tmp_content;
			
			advStatus = advertise.getAdvStatus();
			advType = advertise.getAdvType();
			advName = advertise.getAdvName();
			
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getStartDate());
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(advertise.getEndDate());
			startTime = FastDateFormat.getInstance("HH:mm").format(advertise.getStartDate());
			endTime = FastDateFormat.getInstance("HH:mm").format(advertise.getEndDate());
			
			createUser = advertise.getCreateUser();
			createDate = advertise.getCreateDate();
			modifyUser = advertise.getModifyUser();
			modifyDate = advertise.getModifyDate();
			
			readPropertise(content);
			
			advId = null;
		}
		
		return "editIdxHotSale";
	}
	
	/**
	 * 解析DB中propertise资料
	 * 
	 * @param content
	 * @throws IOException
	 */
	void readPropertise(GenerateContent content) throws IOException {
		Properties prop = new Properties();
		Reader reader = new StringReader(content.getContents());
		prop.load(reader);
		reader.close();
		
		for(int i = 0; i < AD_SIZE; i++) {
			int x = i + 1;
			prodId[i] = StringUtils.defaultString(prop.get("prodId" + x).toString(), "");
			prodName[i] = StringUtils.defaultString(prop.get("prodName" + x).toString(), "");
			brief[i] = StringUtils.defaultString(prop.get("brief" + x).toString(), "");
			if(prop.containsKey("adWord" + x)) 
				adWord[i] = StringUtils.defaultString(prop.get("adWord" + x).toString(), "");
			else 
				adWord[i] = "";
		}
	}
	
	/**
	 * 初始化变数值
	 */
	void initVariables() {
		advertise = new GenerateAdvertise();
		position = new GeneratePosition();
		content = new GenerateContent();

		prodId = new String[AD_SIZE];
		prodName = new String[AD_SIZE];
		brief = new String[AD_SIZE];
		adWord = new String[AD_SIZE];
		startDate = "";
		endDate = "";
		startTime = "";
		endTime = "";
		advName = "";
	}
	
	/**
	 * 必填栏位验证
	 * 
	 * @return
	 */
	boolean idxHotSaleValidate() {
		if(StringUtils.isBlank(advName)) {
			addFieldError("advName", "请输入广告名称");
		}
		
		if(StringUtils.isBlank(startDate)) {
			addFieldError("startDate", "请输入起始日期");
		}
		
		if(StringUtils.isBlank(endDate)) {
			addFieldError("endDate", "请输入结束日期");
		}
		
		if(prodId != null && brief != null && prodName != null) {
			for(int i = 0; i < AD_SIZE; i++) {
				int x = i + 1;
				if(StringUtils.isBlank(prodId[i])) {
					addFieldError("prodId" + x, "請輸入商品编号" + x);
				} else if(!generateService.isProductExist(prodId[i])) {
					addFieldError("prodId" + x, "商品"+x+"可能不存在，或是已被删除，或是不在架上");
				}
				if(StringUtils.isBlank(brief[i])) {
					addFieldError("brief" + x, "请输入商品小标" + x);
				}
				if(StringUtils.isBlank(prodName[i])) {
					addFieldError("prodName" + x, "请输入商品名称" + x);
				}
			}
		} else {
			for(int i = 1; i <= AD_SIZE; i++) {
				addFieldError("prodId" + i, "請輸入商品编号" + i);
				addFieldError("brief" + i, "请输入商品小标" + i);
				addFieldError("prodName" + i, "请输入商品名称" + i);
			}
		}
		
		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
	}
	
	// Getters & Setters
	public String getAdvId() {
		return advId;
	}

	public void setAdvId(String advId) {
		this.advId = advId;
	}

	public String getAdvType() {
		return advType;
	}

	public void setAdvType(String advType) {
		this.advType = advType;
	}

	public String getAdvStatus() {
		return advStatus;
	}

	public void setAdvStatus(String advStatus) {
		this.advStatus = advStatus;
	}

	public String getAdvName() {
		return advName;
	}

	public void setAdvName(String advName) {
		this.advName = advName;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String[] getProdId() {
		return prodId;
	}

	public void setProdId(String[] prodId) {
		this.prodId = prodId;
	}

	public String[] getBrief() {
		return brief;
	}

	public void setBrief(String[] brief) {
		this.brief = brief;
	}

	public String[] getProdName() {
		return prodName;
	}

	public void setProdName(String[] prodName) {
		this.prodName = prodName;
	}

	public String[] getAdWord() {
		return adWord;
	}

	public void setAdWord(String[] adWord) {
		this.adWord = adWord;
	}

	public GenerateService getGenerateService() {
		return generateService;
	}

	public void setGenerateService(GenerateService generateService) {
		this.generateService = generateService;
	}

	public GenerateAdvertise getAdvertise() {
		return advertise;
	}

	public void setAdvertise(GenerateAdvertise advertise) {
		this.advertise = advertise;
	}

	public GeneratePosition getPosition() {
		return position;
	}

	public void setPosition(GeneratePosition position) {
		this.position = position;
	}

	public GenerateContent getContent() {
		return content;
	}

	public void setContent(GenerateContent content) {
		this.content = content;
	}

	public StringBuilder getContents() {
		return contents;
	}

	public void setContents(StringBuilder contents) {
		this.contents = contents;
	}

	public int getAD_SIZE() {
		return AD_SIZE;
	}

	public String getCreateUser() {
		return createUser;
	}

	public void setCreateUser(String createUser) {
		this.createUser = createUser;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getModifyUser() {
		return modifyUser;
	}

	public void setModifyUser(String modifyUser) {
		this.modifyUser = modifyUser;
	}

	public Date getModifyDate() {
		return modifyDate;
	}

	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}
	
}
